package cn.cicoding.controller;

import cn.cicoding.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/user-template")
public class UserMongoTemplateController {

    @Autowired
    private MongoTemplate mongoTemplate;

    @GetMapping("/getAll")
    public void testQuery(){
        //查询字段name为张三的数据（多条件查询）
        Query query = Query.query(Criteria.where("name").is("张三")).with(Sort.by(Sort.Direction.DESC,"age"));

        // 执行查询 模糊查询 只查询5条数据
        Query query1 = Query.query(Criteria.where("name").regex(".*?\\" + "张三" + ".*"));
        query.limit(5);

        List<User> list = mongoTemplate.find(query, User.class);
        List<User> list1 = mongoTemplate.find(query1, User.class);

        System.out.println("list:"+list);
        System.out.println("list1:"+list1);

    }

    @GetMapping("/{userId}")
    public User getByUserId(@PathVariable String userId) {
        User user = mongoTemplate.findById(userId, User.class);
        System.out.println(user);
        //TestDemo(id=661743b77bee2f0a5739819d, name=张三, birthDay=Thu Apr 11 09:58:15 CST 2024)
        return user;
    }

    @GetMapping("/add")
    public void addNewUser() {
        for (int i = 0; i < 10; i++) {
            User user = new User();
            user.setName("张三");
            user.setAge(i);
            user.setCreateTime(new Date());
            mongoTemplate.save(user);
        }
        User testDemo = new User();
        testDemo.setName("张三你吃饭了吗");
        testDemo.setAge(100);
        testDemo.setCreateTime(new Date());
        mongoTemplate.save(testDemo);
        System.out.println("add success!");
    }

    @GetMapping("/delete")
    public void testDel(){
        mongoTemplate.remove(Query.query(Criteria.where("name").is("张三")),User.class);
    }

    @PutMapping("/update")
    public User update(@RequestBody User user) {
        return null;
    }
}
